﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using HangYi_Coffee_Class;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace HangYi_Coffee_Class
{
    public class _DbContext:DbContext
    {
        public DbSet<Order> Orders { get; set; }
        public DbSet<Detail> Details { get; set; }
        public DbSet<Commodity> Commoditys { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Sort> Sorts { get; set; }
        public DbSet<Cup_typeOption> Cup_typeOptions { get; set; }
        public DbSet<IceOption> IceOptions { get; set; }
        public DbSet<TemperatureOption> TemperatureOptions { get; set; }
        public DbSet<SugarOption> SugarOptions { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");
            var configuration = builder.Build();
            string connectString = configuration["DBConnectionStrings:ManagerDB:ConnectionString"]!;
            base.OnConfiguring(optionsBuilder);
            var serverVersion = new MySqlServerVersion(new Version(8, 0, 34));
            optionsBuilder.UseMySql(connectString, serverVersion);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
            modelBuilder.Entity<Commodity>()
                   .HasOne(d => d.Sort)
                   .WithMany(s => s.Commoditys)
                   .HasForeignKey(d => d.SortId);
            modelBuilder.Entity<Address>()
                   .HasOne(a => a.User)
                   .WithMany(s => s.Addresses)
                   .HasForeignKey(d => d.UserId);
        }
        class CommodityConfig : IEntityTypeConfiguration<Commodity>
        {
            public void Configure(EntityTypeBuilder<Commodity> builder)
            {
                builder.HasMany<Cup_typeOption>(u => u.CupTypeOptions).WithOne(d => d.Commodity);
                builder.HasMany<SugarOption>(u => u.SugarOptions).WithOne(d => d.Commodity);
                builder.HasMany<TemperatureOption>(u => u.TemperatureOptions).WithOne(d => d.Commodity);
                builder.HasMany<IceOption>(u => u.IceOptions).WithOne(d => d.Commodity);
            }
        }

    }
}
